window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');
  let gl = getWebGLContext(canvas);
  initShaders(gl, v_shader_source, f_shader_source);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  let position = new Float32Array([
    0.0, 0.5, 10.0, 0.5, -0.5, 20.0, -0.5, -0.5, 30.0
  ]);

  let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
  let u_TranslateMatrix = gl.getUniformLocation(gl.program, 'u_TranslateMatrix');

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  let a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');

  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, position.BYTES_PER_ELEMENT * 3, 0);
  gl.enableVertexAttribArray(a_Position);
  gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, position.BYTES_PER_ELEMENT * 3, position.BYTES_PER_ELEMENT * 2);
  gl.enableVertexAttribArray(a_PointSize);

  let xFormMatrix = new Matrix4();

  let count = 0;
  const rotate = () => {
    xFormMatrix.setRotate(count++, 0, 0, 1);
    xFormMatrix.translate((count % 200) / 100 - 1, 0, 0);
    gl.uniformMatrix4fv(u_TranslateMatrix, false, xFormMatrix.elements);
    gl.uniform4f(u_FragColor, Math.abs(position[0]), Math.abs(position[1]), 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.POINTS, 0, 3);
    requestAnimationFrame(rotate);
  };
  requestAnimationFrame(rotate);
});

const v_shader_source = `
  attribute vec4 a_Position;
  uniform mat4 u_TranslateMatrix;
  attribute float a_PointSize;
  void main(){
    gl_Position = u_TranslateMatrix * a_Position;
    gl_PointSize = a_PointSize;
  }
`;

const f_shader_source = `
  precision mediump float;
  uniform vec4 u_FragColor;
  void main(){
    gl_FragColor = u_FragColor;
  }
`;